<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { School } from '@/api/modules/schools'
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import apiSchool from '@/api/modules/schools'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

// 百度翻译接口
const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}
const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  schoolId: route.params.id as string | number ?? '',
  schoolName: '',
  schoolNameEn: '',
  province: '',
  provinceEn: '',
  city: '',
  cityEn: '',
  level: '',
  levelEn: '',
  schoolLogo: '',
  photoUrl: '',
  schoolIdentifier: '',
  schoolWebsite: '',
  schoolVis: '',
  supervisoryDepartment: '',
  supervisoryDepartmentEn: '',
  characteristics: '',
  characteristicsEn: '',
  schoolIntroduction: '',
  schoolIntroductionEn: '',
  remark: '',
  cooperateOr: 0, // 默认值为 "否"
})

// 特殊字符检验
const validateNoSpecialChars = (value: string) => {
  // 允许字母、数字、汉字、空格、基本标点和中英文逗号，以及 - _ .
  return /[#$%&?]/.test(value) // 移除了 - _ .
}

// 学校名称翻译
const translateSchoolNameToEnglish = async () => {
  if (form.value.schoolName && form.value.schoolName.trim() !== '') {
    form.value.schoolNameEn = await translateToEnglish(form.value.schoolName)
  }
}

// 省份翻译
const translateProvinceToEnglish = async () => {
  if (form.value.province && form.value.province.trim() !== '') {
    form.value.provinceEn = await translateToEnglish(form.value.province)
  }
}

// 城市翻译
const translateCityToEnglish = async () => {
  if (form.value.city && form.value.city.trim() !== '') {
    form.value.cityEn = await translateToEnglish(form.value.city)
  }
}

// 办学层次翻译
const translateLevelToEnglish = async () => {
  if (form.value.level && form.value.level.trim() !== '') {
    form.value.levelEn = await translateToEnglish(form.value.level)
  }
}

// 院校特征翻译
const translateCharacteristicsToEnglish = async () => {
  if (form.value.characteristics && form.value.characteristics.trim() !== '') {
    form.value.characteristicsEn = await translateToEnglish(form.value.characteristics)
  }
}

// 学校简介翻译
const translateIntroductionToEnglish = async () => {
  if (form.value.schoolIntroduction && form.value.schoolIntroduction.trim() !== '') {
    form.value.schoolIntroductionEn = await translateToEnglish(form.value.schoolIntroduction)
  }
}

// 主管部门翻译
const translateDepartmentToEnglish = async () => {
  if (form.value.supervisoryDepartment && form.value.supervisoryDepartment.trim() !== '') {
    form.value.supervisoryDepartmentEn = await translateToEnglish(form.value.supervisoryDepartment)
  }
}

const formRules = ref<FormRules>({
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  schoolNameEn: [
    { required: true, message: '请输入学校英文名称', trigger: 'blur' },
    { max: 250, message: '英文名称不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文名称不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' },
    { max: 50, message: '省份不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  provinceEn: [
    { required: true, message: '请输入省份英文', trigger: 'blur' },
    { max: 250, message: '省份英文不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' },
    { max: 50, message: '城市不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  cityEn: [
    { required: true, message: '请输入城市英文', trigger: 'blur' },
    { max: 250, message: '城市英文不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  level: [
    { required: true, message: '请输入办学层次', trigger: 'blur' },
    { max: 50, message: '办学层次不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  levelEn: [
    { required: true, message: '请输入办学层次英文', trigger: 'blur' },
    { max: 250, message: '办学层次英文不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  schoolLogo: [
    { required: true, message: '请上传学校Logo', trigger: 'change' },
  ],
  photoUrl: [
    { required: true, message: '请上传学校图片', trigger: 'change' },
  ],
  schoolWebsite: [
    { required: true, message: '请输入学校网址', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (!/^https?:\/\/.+\..+/.test(value)) {
          callback(new Error('请输入有效的网址'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  supervisoryDepartment: [
    { required: true, message: '请输入主管部门', trigger: 'blur' },
    { max: 50, message: '主管部门不能超过50个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  supervisoryDepartmentEn: [
    { required: true, message: '请输入主管部门英文', trigger: 'blur' },
    { max: 250, message: '主管部门英文不能超过250个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  schoolIntroduction: [
    { required: true, message: '请输入学校简介', trigger: 'blur' },
    { max: 500, message: '学校简介不能超过500个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  schoolIntroductionEn: [
    { required: true, message: '请输入学校简介英文', trigger: 'blur' },
    { max: 2500, message: '学校简介英文不能超过2500个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文不能包含中文'))
        }
        else if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  schoolIdentifier: [
    { max: 200, message: '学校标识符不能超过100个字符', trigger: 'blur' },
  ],
  schoolVis: [
    { max: 200, message: '学校VIS不能超过100个字符', trigger: 'blur' },
  ],
  remark: [
    { max: 50, message: '备注不能超过20个字符', trigger: 'blur' },
  ],
})

onMounted(() => {
  if (form.value.schoolId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  apiSchool.detail(form.value.schoolId).then((res: any) => {
    loading.value = false
    const data = res.data.data
    form.value.schoolId = data.schoolId
    form.value.schoolName = data.schoolName
    form.value.province = data.province
    form.value.provinceEn = data.provinceEn // 新增
    form.value.city = data.city
    form.value.cityEn = data.cityEn // 新增
    form.value.level = data.level
    form.value.levelEn = data.levelEn // 新增
    form.value.schoolNameEn = data.schoolNameEn
    form.value.schoolIdentifier = data.schoolIdentifier
    form.value.schoolWebsite = data.schoolWebsite
    form.value.schoolVis = data.schoolVis
    form.value.supervisoryDepartment = data.supervisoryDepartment
    form.value.supervisoryDepartmentEn = data.supervisoryDepartmentEn // 新增
    form.value.characteristics = data.characteristics
    form.value.characteristicsEn = data.characteristicsEn // 新增
    form.value.schoolIntroduction = data.schoolIntroduction
    form.value.schoolIntroductionEn = data.schoolIntroductionEn // 新增
    form.value.remark = data.remark
    form.value.cooperateOr = data.cooperateOr
    if (form.value.schoolLogo === '') {
      form.value.schoolLogo = data.schoolLogo
    }
    if (form.value.photoUrl === '') {
      form.value.photoUrl = data.photoUrl
    }
  })
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 构造符合 School 接口的对象
        const schoolData: School = {
          schoolId: Number(form.value.schoolId),
          schoolName: form.value.schoolName,
          province: form.value.province,
          provinceEn: form.value.provinceEn, // 新增
          city: form.value.city,
          cityEn: form.value.cityEn, // 新增
          level: form.value.level,
          levelEn: form.value.levelEn, // 新增
          schoolLogo: form.value.schoolLogo,
          photoUrl: form.value.photoUrl,
          schoolNameEn: form.value.schoolNameEn,
          schoolIdentifier: form.value.schoolIdentifier,
          schoolWebsite: form.value.schoolWebsite,
          schoolVis: form.value.schoolVis,
          supervisoryDepartment: form.value.supervisoryDepartment,
          supervisoryDepartmentEn: form.value.supervisoryDepartmentEn, // 新增
          characteristics: form.value.characteristics,
          characteristicsEn: form.value.characteristicsEn, // 新增
          schoolIntroduction: form.value.schoolIntroduction,
          schoolIntroductionEn: form.value.schoolIntroductionEn, // 新增
          remark: form.value.remark,
          cooperateOr: Number(form.value.cooperateOr),
        }
        if (form.value.schoolId === '') {
          apiSchool.create(schoolData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.schoolId = Number(form.value.schoolId)
          apiSchool.edit(schoolData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'schoolManagement' })
  }
  else {
    router.push({ name: 'schoolManagement' })
  }
}
async function handleLogoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiSchool.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.schoolLogo = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
async function handlePhotoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiSchool.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.photoUrl = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'schoolCreate' ? '新增学校' : '编辑学校'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="学校名称" prop="schoolName">
          <ElInput v-model="form.schoolName" placeholder="请输入学校名称">
            <template #append>
              <ElButton @click="translateSchoolNameToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="学校英文名称" prop="schoolNameEn">
          <ElInput v-model="form.schoolNameEn" placeholder="请输入学校英文名称" />
        </ElFormItem>

        <ElFormItem label="学校标识符" prop="schoolIdentifier">
          <ElInput v-model="form.schoolIdentifier" placeholder="请输入学校标识符" />
        </ElFormItem>

        <ElFormItem label="学校网址" prop="schoolWebsite">
          <ElInput v-model="form.schoolWebsite" placeholder="请输入学校网址" />
        </ElFormItem>

        <ElFormItem label="学校VIS" prop="schoolVis">
          <ElInput v-model="form.schoolVis" placeholder="请输入学校VIS" />
        </ElFormItem>

        <ElFormItem label="主管部门" prop="supervisoryDepartment">
          <ElInput v-model="form.supervisoryDepartment" placeholder="请输入学校的主管部门">
            <template #append>
              <ElButton @click="translateDepartmentToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="主管部门英文" prop="supervisoryDepartmentEn">
          <ElInput v-model="form.supervisoryDepartmentEn" placeholder="请输入学校的主管部门英文" />
        </ElFormItem>

        <ElFormItem label="省份" prop="province">
          <ElInput v-model="form.province" placeholder="请输入省份">
            <template #append>
              <ElButton @click="translateProvinceToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="省份英文" prop="provinceEn">
          <ElInput v-model="form.provinceEn" placeholder="请输入省份英文" />
        </ElFormItem>

        <ElFormItem label="城市" prop="city">
          <ElInput v-model="form.city" placeholder="请输入城市">
            <template #append>
              <ElButton @click="translateCityToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="城市英文" prop="cityEn">
          <ElInput v-model="form.cityEn" placeholder="请输入城市英文" />
        </ElFormItem>

        <ElFormItem label="办学层次" prop="level">
          <ElInput v-model="form.level" placeholder="请输入办学层次">
            <template #append>
              <ElButton @click="translateLevelToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="办学层次英文" prop="levelEn">
          <ElInput v-model="form.levelEn" placeholder="请输入办学层次英文" />
        </ElFormItem>

        <ElFormItem label="院校特征" prop="characteristics">
          <ElInput v-model="form.characteristics" placeholder="请输入院校特征（用'、'隔开）">
            <template #append>
              <ElButton @click="translateCharacteristicsToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="院校特征英文" prop="characteristicsEn">
          <ElInput v-model="form.characteristicsEn" placeholder="请输入院校特征英文（用'、'隔开）" />
        </ElFormItem>

        <ElFormItem label="学校简介" prop="schoolIntroduction">
          <ElInput v-model="form.schoolIntroduction" placeholder="请输入学校简介">
            <template #append>
              <ElButton @click="translateIntroductionToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="学校简介英文" prop="schoolIntroductionEn">
          <ElInput v-model="form.schoolIntroductionEn" placeholder="请输入学校简介英文" />
        </ElFormItem>

        <ElFormItem label="院校备注" prop="remark">
          <ElInput v-model="form.remark" placeholder="请输入院校备注" />
        </ElFormItem>

        <ElFormItem label="是否合作" prop="cooperateOr">
          <ElSwitch
            v-model="form.cooperateOr"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            inline-prompt
          />
        </ElFormItem>

        <ElFormItem label="上传logo" prop="schoolLogo">
          <ImageUpload v-model="form.schoolLogo" :loading="updateImg" action="" name="schoolLogo" :width="150" :height="150" :http-request="handleLogoSuccess" />
        </ElFormItem>

        <ElFormItem label="上传学校图片" prop="photoUrl">
          <ImageUpload v-model="form.photoUrl" :loading="updateImg" action="" name="photoUrl" :width="150" :height="150" :http-request="handlePhotoSuccess" />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
